package com.lanjing.common.redis.configure;

import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * 内容摘要:Redis配置的类
 *
 * @author: zyt
 * @date 2024-01-16 10:42
 */
@Configuration
public class RedisConfig {

    @Resource
    private RedisConnectionFactory redisConnectionFactory;

    @Bean
    @SuppressWarnings(value = { "unchecked", "rawtypes" })
//    @ConditionalOnSingleCandidate
    public RedisTemplate<Object,Object> redisTemplate(){
        // 创建RedisTemplate对象
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();

        // 设置RedisConnection工厂 实现多种Java Redis客户端接入的工厂
        redisTemplate.setConnectionFactory(redisConnectionFactory);

        FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer<>(Object.class);
//        FastJsonRedisSerializer serializer = new FastJsonRedisSerializer(Object.class);

        // 使用StringRedisSerializer来序列化和反序列化redis的key值
//        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setKeySerializer(new FastJson2JsonRedisSerializer<>(Object.class));
        redisTemplate.setValueSerializer(serializer);

        // Hash的key也采用StringRedisSerializer的序列化方式
        redisTemplate.setHashKeySerializer(new FastJson2JsonRedisSerializer<>(Object.class));
        redisTemplate.setHashValueSerializer(serializer);

        redisTemplate.afterPropertiesSet();

        return redisTemplate;

    }
}
